package cn.commander.controller;

import cn.commander.base.BaseController;
import cn.commander.constant.MvcResponseConstant;
import cn.commander.utils.RSAUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: RsaController <br/>
 * Author: zhongyi_yang <br/>
 * Description:  <br/>
 * Version: 1.0 <br/>
 * Date: 2018/5/28 9:20 <br/>
 * To change this template use File | Settings | File Templates.
 */
@RestController
@RequestMapping("/v1/rsa")
public class RsaController extends BaseController {
	/**
	 * 生成公钥
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getkey", method = RequestMethod.GET)
	public Object getPublicKey(HttpServletRequest request) throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		KeyPair kp = RSAUtil.generateKeyPair(request);
		RSAPublicKey pubk = (RSAPublicKey) kp.getPublic();// 生成公钥
		RSAPrivateKey prik = (RSAPrivateKey) kp.getPrivate();// 生成私钥

		String publicKeyExponent = pubk.getPublicExponent().toString(16);// 16进制
		String publicKeyModulus = pubk.getModulus().toString(16);// 16进制
		request.getSession().setAttribute("prik", prik);
		result.put("pubexponent", publicKeyExponent);
		result.put("pubmodules", publicKeyModulus);
		return getResponseData().buildResponseData(MvcResponseConstant.CODE_00000, result);
	}
}
